import { useRef, FC, ReactElement } from 'react';
import { ITodo } from '../typings';

interface IProps {
  addTodo: (todo: ITodo) => void;
  todoList: ITodo[];
}
const TdInput: FC<IProps> = ({ addTodo, todoList }): ReactElement => {
  const addItem = (): void => {
    const val: string = inputRef.current!.value.trim();
    if (val.length) {
      const isExist = todoList.find(todo => todo.content === val);
      if (isExist) {
        return alert('已存在该事项！');
      }
      addTodo({
        id: new Date().getTime(),
        completed: false,
        content: val,
      });
      inputRef.current!.value = '';
    }
    return;
  };
  const inputRef = useRef<HTMLInputElement>(null);

  return (
    <div className={'td-input'}>
      <input ref={inputRef} type="text" placeholder="请输入待办事项" />
      <button onClick={addItem}>添加</button>
    </div>
  );
};

export default TdInput;
